package com.example.util;

import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

public class EnhancedGetUrlBuilder {


    private final String baseUrl;
    private final Map<String, Object> parameters;
    private boolean encodeValues = true;

    public EnhancedGetUrlBuilder(String baseUrl) {
        this.baseUrl = baseUrl;
        this.parameters = new LinkedHashMap<>(); // 保持参数顺序
    }

    /**
     * 创建生成器实例
     */
    public static EnhancedGetUrlBuilder from(String baseUrl) {
        return new EnhancedGetUrlBuilder(baseUrl);
    }

    /**
     * 添加单个参数
     */
    public EnhancedGetUrlBuilder param(String key, Object value) {
        if (key != null && value != null) {
            parameters.put(key, value);
        }
        return this;
    }

    /**
     * 添加多个参数
     */
    public EnhancedGetUrlBuilder params(Map<String, Object> params) {
        if (params != null) {
            parameters.putAll(params);
        }
        return this;
    }

    /**
     * 添加 JSON 字符串参数（平铺展开）
     */
    public EnhancedGetUrlBuilder jsonParams(JSONObject jsonParams) {
        try {
            Map<String, Object> params = jsonParams.getInnerMap();
            return params(params);
        } catch (Exception e) {
            throw new RuntimeException("Invalid JSON parameters: " + jsonParams, e);
        }
    }

    /**
     * 添加数组参数（支持多个相同参数名）
     */
    public EnhancedGetUrlBuilder arrayParam(String key, Object... values) {
        if (key != null && values != null && values.length > 0) {
            parameters.put(key, Arrays.stream(values)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList()));
        }
        return this;
    }

    /**
     * 设置是否对值进行 URL 编码（默认开启）
     */
    public EnhancedGetUrlBuilder encodeValues(boolean encode) {
        this.encodeValues = encode;
        return this;
    }

    /**
     * 构建查询字符串
     */
    private String buildQueryString() {
        if (parameters.isEmpty()) {
            return "";
        }

        List<String> queryParams = new ArrayList<>();

        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            String key = encodeValue(entry.getKey());
            Object value = entry.getValue();

            if (value instanceof Collection) {
                // 处理集合类型
                ((Collection<?>) value).forEach(item -> {
                    if (item != null) {
                        queryParams.add(key + "=" + encodeValue(item.toString()));
                    }
                });
            } else if (value instanceof Object[]) {
                // 处理数组类型
                Arrays.stream((Object[]) value)
                        .filter(Objects::nonNull)
                        .forEach(item -> {
                            queryParams.add(key + "=" + encodeValue(item.toString()));
                        });
            } else {
                // 处理单个值
                queryParams.add(key + "=" + encodeValue(value.toString()));
            }
        }

        return String.join("&", queryParams);
    }

    /**
     * URL 编码
     */
    private String encodeValue(String value) {
        if (!encodeValues) {
            return value;
        }
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("URL encoding failed", e);
        }
    }

    /**
     * 构建完整的 URL
     */
    public String build() {
        String queryString = buildQueryString();
        if (!queryString.isEmpty()) {
            return baseUrl + "?" + queryString;
        }
        return baseUrl;
    }

    /**
     * 获取参数 Map（只读）
     */
    public Map<String, Object> getParameters() {
        return Collections.unmodifiableMap(parameters);
    }

    /**
     * 清空所有参数
     */
    public EnhancedGetUrlBuilder clear() {
        parameters.clear();
        return this;
    }

    @Override
    public String toString() {
        return build();
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        EnhancedGetUrlBuilder enhancedGetUrlBuilder=new EnhancedGetUrlBuilder("https://www.baidu.com");
        enhancedGetUrlBuilder.params(map);
        System.out.println(enhancedGetUrlBuilder.build());
    }
}
